﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Xml;
using IMT;
using GPM.QuickQuote.Logging;


namespace IMTApp
{
    /// <summary>
    /// Author: Elliott Perry 01/09/2011
    /// 
    /// Parent Class of all messages which deals with 
    ///     -Sending (Done 01/09/2011)
    ///     -Saving (Done 01/09/2011)
    ///     -Updating IBS 
    ///     -Generating the XML? (Done 3/09/2011)
    ///     -Attaching Docs to XML (Done - In child class)
    ///    
    /// </summary>
    public class XMLMessage
    {


        public string savePath;
        GpmLogger logger = new GpmLogger();

        /// <summary>
        /// This method saves the XML data into an XML file in the correct location.
        /// </summary>
        /// <param name="data"></param>
        public void SaveXml(string data)
        {
            try
            {

                string currentSavePath = GlobalData.XMLMsgPath + @"MSG " + getTimeStamp() + ".XML";

                logger.LogInfo("DEBUG: Trying to save to " + currentSavePath);

                TextWriter writer = new StreamWriter(currentSavePath);

                //Tidy up
                writer.Write(data);
                writer.Close();

                
                //update savePath variable so that this data can be referenced when sending to LS
                savePath = currentSavePath;

                logger.LogInfo(".... Save Successful");


                //send to LimeStreet
                sendToLSTEST(data,currentSavePath);
            }
            catch (Exception e)
            {
                logger.LogInfo("\nERROR: SaveXML (XMLMessage) Problem Saving File: " + e);
            }

        }



        /// <summary>
        /// This method calls the Lime Street web-service, sends the message.
        /// 
        ///     to-Do
        ///        -Deal with the return message from LS.
        /// </summary>
        /// <param name="xmlSendData"></param>
        public void sendToLSTEST(string xmlSendData, string savePath)
        {
            
            
            IMT.LSTest.Placing LSConnector = new IMT.LSTest.Placing();
            var xmlToSend = new XmlDocument();
            xmlToSend.LoadXml(xmlSendData);
            XmlNodeList xmlList1 = xmlToSend.SelectNodes("/Package/Workflow/Operation");

            string strXML = xmlList1.Item(0).InnerText;
            string responseFromLS;
            if (strXML == "SubmitEndorsement")
            {
                //Send the message onto Lime Street and return the status of the message into the string
                 responseFromLS = LSConnector.SubmitEndorsementXml(xmlSendData);

            }
            else
            {
                responseFromLS = LSConnector.QueryEndorsement(xmlSendData);
            }
           
           
           
            logger.LogInfo("Response from LS Test:" + responseFromLS);

            //write response to an XML document
            XmlDocument LSResponse = new XmlDocument();
            LSResponse.LoadXml(responseFromLS.ToString());

            

            XmlNodeList xnList = LSResponse.SelectNodes("/Package/Workflow/Status");


            if (xnList.Item(0).InnerText == "Failure")
            {
                logger.LogError(responseFromLS.ToString());
                //logger.LogError("Lime Street Reply Message Fail: " + responseFromLS.ToString());
            }
            
            
            //build reply save path
            savePath = savePath.Insert(savePath.Length - 4, " REPLY");

            try
            {
                logger.LogInfo("DEBUG: Trying to save response to " + savePath);

                TextWriter writer = new StreamWriter(savePath);

                //Tidy up
                writer.Write(LSResponse.OuterXml.ToString());
                writer.Close();

                logger.LogInfo(".... Save Reply Successful");
            }
            catch(Exception e)
            {
                logger.LogInfo("ERROR: Saving Response -" + e);
                
            }
            
           

        }


        /// <summary>
        /// This method returns the current time in a timestamp so that it can be used for in file names and log files.
        /// </summary>
        /// <returns></returns>
        public string getTimeStamp()
        {
           

            string timeStamp = DateTime.Now.ToString("yyyy MM dd HH mm ss");

            return timeStamp;

        }

        public string generateSecurityToken()
        {
            string dataToEncrypy = "##gpm-sharon-stanley##SS111abc1!";
            string encryptionKey = "GPM_20111013";
            string encryptedToken;

            MD5 md5 = new MD5CryptoServiceProvider();
            TripleDES des = new TripleDESCryptoServiceProvider();
            des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(encryptionKey));
            des.IV = new byte[des.BlockSize / 8];
            ICryptoTransform ct = des.CreateEncryptor();
            byte[] payload = Encoding.Unicode.GetBytes(dataToEncrypy);
            byte[] transformKey = ct.TransformFinalBlock(payload, 0, payload.Length);
            
            encryptedToken = Convert.ToBase64String(transformKey);

            return encryptedToken;
        }


        public string convertDocumentToBase64(string docPath)
        {
            
            string strWordInBase64;

            //Create base64 string to store the converted output
            FileStream inputStream = new FileStream(docPath, FileMode.Open);

            
            //create the array for storing data read in
            byte[] wordData = new byte[inputStream.Length];

            //move stream into array
            inputStream.Read(wordData, 0, wordData.Length);

            //pass array into String after converting to base64
            strWordInBase64 = Convert.ToBase64String(wordData);

            //Clean up
            inputStream.Close();

            return strWordInBase64;


        }

    }
}
